package com.ttscm.srds.utils;

/**
 * https://www.nhooo.com/note/qa01r7.html
 *
 * @version:
 * @author:
 * @className:
 * @packageName:
 * @description:
 * @date: 2022/07/19
 */
public final class HexUtil {
    public static String str2Hex(String sourceStr) {
        StringBuffer targetHex = new StringBuffer();
        char[] sourceChars = sourceStr.toCharArray();
        for (int i = 0; i < sourceChars.length; i++) {
            String hexString = Integer.toHexString(sourceChars[i]).toUpperCase();
            targetHex.append(hexString);
        }
        return targetHex.toString();
    }

    public static String hex2Str(String sourceHex) {
        String targetStr = new String();
        char[] sourceChars = sourceHex.toCharArray();
        for (int i = 0; i < sourceChars.length; i = i + 2) {
            String hexStr = "" + sourceChars[i] + "" + sourceChars[i + 1];
            char targetChar = (char) Integer.parseInt(hexStr, 16);
            targetStr = targetStr + targetChar;
        }
        return targetStr;
    }

    public static String leadingZero(String srHex, int len) {
        return String.format("%" + len * 2 + "s", srHex).replace(" ", "0");
    }
}
